/* ==================================== 全局变量 开始*/
// ----------------------------------

// 按钮容器div
let buttonContainer = $("div.order3.clearfix.layui-form");
// 语言列表
const languages = ["en", "fr", "de", "it", "es", "nl", "sv", "pl"];

// ----------------------------------
/* ==================================== 全局变量 结束*/
/* ==================================== 全局方法 开始*/
// ----------------------------------
// --- 消息提示
function msgTip(msg, icon, time) {
    const script = document.createElement("script");
    script.textContent =
        `
        (function() {
                layer.msg("` +
        msg +
        `", {anim: 0,offset:'auto',time: ` +
        time +
        `});
        })();
    `;
    document.head.appendChild(script);
    document.head.removeChild(script);
}

// --- 获取选中产品的ID
function getCheckedId() {
    let ids = []; // 用于存储选中的ID
    // 遍历表格的每一行
    $("div.layui-table-body.layui-table-main > table > tbody > tr").each(
        function () {
            let $row = $(this);
            // 检查第一格中的复选框是否被选中
            let isChecked = $row
                .find("td:first input[type='checkbox']")
                .is(":checked");
            if (isChecked) {
                // 如果复选框被选中，获取第二格中的ID值
                let id = $row.find("td:eq(1) .layui-table-cell").text().trim();
                // 将ID值存储到列表中
                ids.push(id);
            }
        }
    );
    return ids;
}

// --- 检查标题是否重复
function checkDuplicateTitles(result) {
    const duplicates = []; // 存储最终结果
    const titleMap = {}; // 结构: { en: { "标题A": [id1, id2], "标题B": [id3] }, ... }
    // 初始化语言映射
    languages.forEach((lang) => {
        titleMap[lang] = {};
    });

    // 遍历每个产品
    Object.entries(result).forEach(([id, product]) => {
        // 遍历每个语言
        languages.forEach((lang) => {
            const title = product[lang]?.title?.trim(); // 获取标题并去除首尾空格
            if (title) {
                // 仅处理非空标题
                if (!titleMap[lang][title]) {
                    titleMap[lang][title] = [];
                }
                titleMap[lang][title].push(id);
            }
        });
    });
    // 检查重复项
    languages.forEach((lang) => {
        const titles = titleMap[lang];
        Object.entries(titles).forEach(([title, ids]) => {
            if (ids.length > 1) {
                // 同一标题有多个ID则视为重复
                duplicates.push({
                    country: lang,
                    ids: ids,
                    title: title,
                });
            }
        });
    });
    return duplicates;
}

// --- 检查标题长度
function checkValidateTitles(result) {
    const finalResult = {}; // 最终结构为 { id1: { en: {...}, fr: {...} }, ... }
    // 遍历每个产品
    for (const id in result) {
        if (!result.hasOwnProperty(id)) continue;

        const product = result[id];
        const idErrors = {}; // 当前ID的所有国家标题错误

        for (const lang of languages) {
            const title = product[lang]?.title;
            // console.log(lang,title);
            const variants = product.variants;
            const errorDetail = {};

            // 检查标题是否为空
            if (title.length === 0) {
                // console.log('标题为空');
                Object.assign(errorDetail, {
                    错误类型: "标题为空",
                    标题内容: title || "空",
                    变体有无: Object.keys(variants).length > 0 ? "有" : "无",
                });
                // console.log(errorDetail);
            // 计算标题+变体总长度
            } else {
                // 计算标题总长度
                let maxVariantLength = 0;
                if (variants) maxVariantLength = Math.max(...Object.keys(variants).map((v) => v.length)) + 2;
                const totalLength = title.length + maxVariantLength;

                // 检查长度限制
                if (variants && totalLength > 200) {
                    Object.assign(errorDetail, {
                        错误类型: "标题+变体字符超出",
                        标题字符: title.length,
                        变体字符: maxVariantLength,
                        总字符数: totalLength,
                    });
                } else if (!variants && title.length > 200) {
                    Object.assign(errorDetail, {
                        错误类型: "标题超长",
                        标题字符: title.length,
                    });
                }
            }

            // 如果有错误才保存
            if (Object.keys(errorDetail).length > 0) {
                idErrors[lang] = errorDetail;
                // console.log(idErrors[lang]);
            }
        }

        // 如果当前ID有错误，才存入最终结果
        if (Object.keys(idErrors).length > 0) finalResult[id] = idErrors;
    }
    // console.log(finalResult);
    return finalResult;
}

// --- 检查变体和成本
function validateProductsPricing(result) {
    const errorMap = {}; // 结构为 { id1: { 错误类型1: [...], 错误类型2: [...] }, ... }

    for (const id in result) {
        if (!result.hasOwnProperty(id)) continue;
        const product = result[id];
        const variants = product.variants;

        // 初始化当前ID的错误容器
        const idErrors = {};

        // 检查变体
        if (Object.keys(variants).length > 0) {
            for (const variant in variants) {
                if (variants.hasOwnProperty(variant)) {
                    // 检查非法字符
                    if (variant.includes("--")) idErrors["变体名"] = "异常";

                    // 检查价格为0
                    const price = parseFloat(variants[variant]);
                    if (price === 0) idErrors["变体价格"] = "异常";
                }
            }
        } else {
            // 检查默认值
            const cost = parseFloat(product.cost);
            const weight = parseFloat(product.weight);

            if (cost === 100 && weight === 5) {
                idErrors["成本和重量"] = {
                    成本: cost,
                    重量: weight,
                };
            }
        }
        // 仅当存在错误时保存到最终结果
        if (Object.keys(idErrors).length > 0) errorMap[id] = idErrors;
    }

    return errorMap;
}

// --- 检查五点和描述
function checkContentAndDescript(result) {
    const errorsObj = {};

    for (const id in result) {
        const idErrors = {};

        for (const lang of languages) {
            const langData = result[id][lang];
            const contentPoints = langData.content.split("\n").map((p) => p.trim());
            const errors = {};
            if (contentPoints.length === 5) {
                const invalidPoints = {};
                for (let i = 0; i < contentPoints.length; i++) {
                    let p = i + 1;
                    const len = contentPoints[i].length;
                    if (len < 80) invalidPoints[p] = "低于80";
                    if (len > 500) invalidPoints[p] = "大于500";
                }

                // 记录异常五点
                if (invalidPoints.length > 0) {
                    errors.五点 = invalidPoints;
                }
            } else errors.五点 = "数量异常：" + contentPoints.length;

            // 检查描述字符数
            if (langData.descript.length === 0)
                errors.描述 = "描述缺失：" + langData.descript.length;
            if (langData.descript.length > 1900)
                errors.描述 = "字符数超出：" + langData.descript.length;

            // 仅保留有异常的语种
            if (Object.keys(errors).length > 0) idErrors[lang] = errors;
        }

        // 仅保留有异常的ID
        if (Object.keys(idErrors).length > 0) errorsObj[id] = idErrors;
    }

    return errorsObj;
}

// ----------------------------------
/* ==================================== 全局方法 结束*/
// ----------------------------------
// --- 打开选中按钮
let openCheckedButton = $('<a id="open_all" style="width: 100px; float:left;background-color:#19a119;"><img src="img/c8.png" alt="">打开产品</a>');
openCheckedButton.click(function () {
    let ids = getCheckedId();
    // 输出选中的ID列表
    console.log('选中的ID列表:', ids);
    if (ids.length === 0) msgTip("请选择要打开的产品");
    else {
        ids.forEach(function (id) {
            // 拼接链接
            var url = "http://erp.kuandar.com/admin/products_edit.php?id=" + id + "&if_head=1";
            // 在新标签页中打开链接
            window.open(url, "_blank");
        });
    }
});
buttonContainer.append(openCheckedButton);


// --- 检查异常按钮
let checkExceptionButton = $('<a id="check_titles" style="width: 100px; float:left;background-color:#19a119;"><img src="img/c4.png" alt="">检查产品</a>');
checkExceptionButton.click(function () {
    var ids = getCheckedId();
    let result = {};
    if (ids.length === 0) msgTip("请选择要检查的产品");
    else {
        // 使用 Promise 等待所有 AJAX 请求完成
        const promises = ids.map((id) => {
            return new Promise((resolve, reject) => {
                result[id] = {};
                var url = `http://erp.kuandar.com/admin/products_edit.php?id=${id}&if_head=1`;
                var settings = {
                    url: url,
                    method: "GET",
                    timeout: 0,
                    withCredentials: true,
                    dataType: "html",
                };

                $.ajax(settings)
                    .done(function (response) {
                        var $html = $(response);
                        // 成本
                        result[id].cost = $html.find("#chengben").val();
                        // 重量
                        result[id].weight = $html.find("#zhongliang").val();
                        // 变体和价格
                        result[id].variants = {};
                        $html.find("table.btcon.layui-table tbody tr").each(function () {
                            const $row = $(this);
                            const variant = $row.find("td:eq(1)").text().trim();
                            const price = $row.find("td:eq(3) input.bt_price").val().trim();
                            if (variant && price) {
                                result[id].variants[variant] = price;
                            }
                        });
                        // 不同国家的内容
                        for (let j = 0; j < languages.length; j++) {
                            result[id][languages[j]] = {
                                title: $html.find("#" + languages[j] + "title").val(),
                                keyword: $html.find("#" + languages[j] + "keyword").val(),
                                content: $html.find("#" + languages[j] + "content").val(),
                                descript: $html.find("#" + languages[j] + "descript").val(),
                            };
                        }
                        resolve(); // 标记此请求完成
                    })
                    .fail(reject);
            });
        });

        // 等待所有请求完成后再输出结果
        Promise.all(promises)
            .then(() => {
                // console.log(result);
                console.clear(); //清空控制台

                const duplicates = checkDuplicateTitles(result);
                console.log("标题重复：",Object.keys(duplicates).length > 0 ? duplicates : "无");

                const validateTitles = checkValidateTitles(result);
                console.log("标题长度：",Object.keys(validateTitles).length > 0 ? validateTitles : "无");

                const checkResults = validateProductsPricing(result);
                console.log("变体和成本:",Object.keys(checkResults).length > 0 ? checkResults : "无");

                const checkContent = checkContentAndDescript(result);
                console.log("五点和描述:",Object.keys(checkContent).length > 0 ? checkContent : "无");
            })
            .catch((error) => {
                console.error("请求失败:", error);
            });
    }
});
buttonContainer.append(checkExceptionButton);

// --- 导出选中按钮
function dao_chu(flag) {
    const ids = getCheckedId();
    if (ids.length === 0) {msgTip("请选择要导出的产品"); return}

    const urlBase = `http://erp.kuandar.com/admin/action/daochu_action.php?cpid=${ids}`;

    // 结构化国家配置参数
    let countriesConfig = [
        { guojia: 1, yuyan: 8, daima: "US" },
        { guojia: 2, yuyan: 0, daima: "CA" },
        { guojia: 3, yuyan: 0, daima: "UK" },
        {guojia: 5,yuyan: 2,daima: "DE"},
        { guojia: 4, yuyan: 1, daima: "FR" },
        { guojia: 6, yuyan: 3, daima: "IT" },
        { guojia: 7, yuyan: 4, daima: "ES" },
        { guojia: 10, yuyan: 4, daima: "MX" },
        { guojia: 14, yuyan: 9, daima: "NL" },
        { guojia: 16, yuyan: 10, daima: "SE" },
        { guojia: 17, yuyan: 11, daima: "PL" },
    ];
    // 动态生成URL参数
    const generateParams = ({ guojia, yuyan, daima }) =>
        `&guojia=${guojia}&yuyan=${yuyan}&daima=${daima}&typeid=`;
    // 条件添加德国配置
    switch (flag) {
        case "Y":
            break;
        case "N":
            countriesConfig = countriesConfig.filter((country => country.daima !== "DE"));
            break;
        case "M":
            countriesConfig = countriesConfig.filter(country =>["US", "CA", "MX"].includes(country.daima));
            break;
        case "O":
            countriesConfig = countriesConfig.filter(country =>!["US", "CA", "MX"].includes(country.daima));
            break;
    }
    console.log(countriesConfig)
    // 批量处理URL
    countriesConfig.map((config) => `${urlBase}${generateParams(config)}`)
        .forEach((url, index) => {
            setTimeout(() => window.open(url, "_blank"), index * 300);
        });
}

buttonContainer.append(
    $('<a id="" style="width: 120px; float:left;background-color:#19a119;">导出：带德国</a>').click(function () {
        dao_chu("Y");
    })
);

buttonContainer.append(
    $('<a id="" style="width: 120px; float:left;background-color:#19a119;">导出：不带德国</a>').click(function () {
        dao_chu("N");
    })
);

buttonContainer.append(
    $('<a id="" style="width: 100px; float:left;background-color:#19a119;">导出：美洲</a>').click(function () {
        dao_chu("M");
    })
);

buttonContainer.append(
    $('<a id="" style="width: 100px; float:left;background-color:#19a119;">导出：欧洲</a>').click(function () {
        dao_chu("O");
    })
);

window.onload = function() {
    setTimeout(function() {
        // document.querySelector("#start").value = getFormattedDate();
        console.log(document.querySelector("#start").value)
    if (document.querySelector("body > div.x-body > div.wdcp > ul")) {
        document.querySelector("body > div.x-body > div.wdcp > ul").remove();
        document.querySelector("body > div.x-body > div.wdcp > div.layui-form.layui-border-box.layui-table-view").style.height = "680px";
        document.querySelector("body > div.x-body > div.wdcp > div.layui-form.layui-border-box.layui-table-view > div.layui-table-box").style.height = "639px";
        document.querySelector("body > div.x-body > div.wdcp > div.layui-form.layui-border-box.layui-table-view > div.layui-table-box > div.layui-table-body.layui-table-main").style.height = "600px";
        // 采集产品
        document.querySelector("body > div.x-body > div.wdcp > div.order3.clearfix.layui-form > a.a4.fl").remove();
        // 立即刊登
        document.querySelector("body > div.x-body > div.wdcp > div.order3.clearfix.layui-form > a.a1.fl.a7").remove();
        // 范围删除
        document.querySelector("body > div.x-body > div.wdcp > div.order3.clearfix.layui-form > a.a12.fl").remove();
    }
    }, 500);  // 1000毫秒=1秒
};


function getFormattedDate() {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function getTwoMonths(dateStr,n) {
    const date = new Date(dateStr);
    date.setMonth(date.getMonth() +n);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}


// 产品编号
document.querySelector("body > div.x-body > form > div > div > input:nth-child(8)").remove();
// 业务员
document.querySelector("body > div.x-body > form > div > div > div:nth-child(8)").remove();
// 公司名称
document.querySelector("body > div.x-body > form > div > div > div.fl.gs").remove();

let form_container = document.querySelector("body > div.x-body > form > div > div");

let b = document.querySelector("#start").value;
let e = document.querySelector("#end").value;
let begin = document.createElement("input");
begin.type = "button";
begin.className = "layui-btn fl";
begin.value = "前两个月";
begin.addEventListener("click", function() {
    if (e==='') e = getFormattedDate();
    else e = b
    b = getTwoMonths(e,-2);
    document.querySelector("#start").value = b
    document.querySelector("#end").value = e
    console.log(b, e)
});

let end = document.createElement("input");
end.type = "button";
end.className = "layui-btn fl";
end.value = "后两个月";
end.addEventListener("click", function() {
    console.log(b, e)
    if (e==='') e = getTwoMonths(b,+2);
    else e = getTwoMonths(e,+2);
    b = getTwoMonths(e,-2);
    document.querySelector("#start").value = b
    document.querySelector("#end").value = e
    console.log(b, e)
});
form_container.append(begin, end);


